package com.liu.controller;

import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.*;

import com.liu.model.User;
import com.liu.model.UserDao;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/uploadServlet")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(11);
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("utf-8");
        //表单
        String myFile = "";
        //核心Api
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //判断是否是muitipart/form-data类型
        if(!ServletFileUpload.isMultipartContent(req)) {
            //resp.getWriter().println("表单的enctype属性不是multipart/form-data类型");
            System.out.println("表单的enctype属性不是multipart/form-data类型");
            return;
        }
        //设置单个文件上传大小 8M
        fileUpload.setFileSizeMax(8*1024*1024);
        //设置总上传文件大小(有时候一次性上传多个文件，需要有一个上限,此处为60M)
        fileUpload.setSizeMax(60*1024*1024);
        //设置上传监听器[参数为自定义的监听器]
        // fileUpload.setProgressListener(new ListenerUploadProgress());
        //解析请求
        try {
            List<FileItem> parseRequest = fileUpload.parseRequest(req);
            //获取数据
            for (FileItem fileItem : parseRequest) {
                //判断数据类型是不是普通的form表单字段
                if(!fileItem.isFormField()) {
                    //上传文件
                    String fileName = fileItem.getName();
                    InputStream fileStream = fileItem.getInputStream();
                    //定义保存的父路径（服务器部署相对的绝对路径）
                    String parentDir = this.getServletContext().getRealPath("/userImage");
                    //使用UUID+文件名的方式，避免文件重名
                    String realFileName = UUID.randomUUID().toString()+"-"+fileName;
                    //创建要保存的文件
                    File file = new File(parentDir,realFileName);
                    //判断文件夹是否存在
                    if(!file.getParentFile().exists()) {
                        //创建文件夹[多级文件夹]file.madir是创建单一文件夹
                        file.getParentFile().mkdirs();
                    }
                    //创建输出流
                    OutputStream out = new FileOutputStream(file);
                    //创建字节缓存
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    //一次读取1kb(1024byte),返回-1表明读取完毕
                    while((len = fileStream.read(buffer))!=-1) {
                        //一次写入1kb(1024byte)
                        out.write(buffer,0, len);
                    }
                    System.out.println(parentDir);
                    System.out.println(realFileName);
                    myFile = realFileName;
                    //冲刷流资源
                    out.flush();
                    //关闭流
                    out.close();
                    fileStream.close();
                }else {
                    //普通字段  //字段名
                    String fieldName = fileItem.getFieldName();
                    //字段值中文乱码
                    String fieldValue = fileItem.getString("UTF-8");
                    System.out.println(fieldName+":"+fieldValue);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        if (myFile.equals("") ||
                !(myFile.substring(myFile.length() - 4).equals(".png") ||
                myFile.substring(myFile.length() - 4).equals(".jpg"))) {
            System.out.println(myFile.substring(myFile.length() - 4));
            resp.getWriter().write("未上传头像！");
            return;
        }


        //将图片的路径存储到数据库
        UserDao userDao = new UserDao();
        HttpSession session = req.getSession(true);
        User user = (User)session.getAttribute("user");
        int userId = user.getUserId();
        userDao.uploadImageURL(myFile, userId);
        User newUser = userDao.selectById(user.getUserId());
        session.setAttribute("user", newUser);
        resp.getWriter().print("上传成功！");
    }
}
